<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible &&
        !bindingProductInfo.visible &&
        !detailsInfo.visible
      "
      v-if="$permission('smartCabinetList:list')"
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :queryMoreJson="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :slipSelectRequest="slipSelectRequest"
          :clearType="clearType"
        >
        </new-page-filter>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-remove>
            <el-button :disabled="!canRemove" @click="remove">删除</el-button>
          </template>
          <template v-slot:filter-enable>
            <el-button :disabled="!canEnable" @click="enable">启用</el-button>
          </template>
          <template v-slot:filter-disable>
            <el-button :disabled="!canDisable" @click="disable">停用</el-button>
          </template>
        </new-page-filter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true"
            >偏好设置
          </el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :checkBox="true"
        :tabIndex="true"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassOtherName"
        @sortChange="sortChange"
        @pageInfo="pageInfo"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-name="scope">
          <span
            v-if="scope.row.name"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.name }}</span
          >
          <span v-else>-</span>
        </template>
      </table-container>
    </div>
    <!--偏好 -->
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      @callback="setPreferenceCallback"
    />
    <!-- 详情-->
    <Details
      v-if="detailsInfo.visible"
      v-model:visible="detailsInfo.visible"
      :title="detailsInfo.title"
      :id="detailsInfo.id"
      @returnBack="getList"
    />
    <!-- 新增 -->
    <modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      @returnModify="returnModify"
    />
    <!-- 修改或绑定产品 -->
    <bindingProduct
      v-if="bindingProductInfo.visible"
      v-model:visible="bindingProductInfo.visible"
      :title="bindingProductInfo.title"
      :type="bindingProductInfo.type"
      :id="bindingProductInfo.id"
      @returnModify="returnModify"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:formData="advancedSearchInfo.data"
      :fieldList="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
  </div>
</template>

<script setup name="smartCabinetList">
import Modify from './modify'
import BindingProduct from './bindingProduct'
import Details from './details'
import axios from 'axios'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import {
  enabledSmartCabinet,
  disabledSmartCabinet,
  deleteSmartCabinet,
  getSmartCabinetCustomizeListPage,
} from '@/api/smartCabinet'

const { proxy } = getCurrentInstance()

// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  query: {
    groupMap: {},
    groups: [],
    sortString: '',
    queryMap: {
      depotAuth: {
        asTbName: 'smart_cabinet_list',
        columnName: 'depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'depotAuth',
      },
      deptAuth: {
        asTbName: 'smart_cabinet_list',
        columnName: 'dept_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'deptAuth',
      },
    },
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('smartCabinetList:add'),
    },
    {
      type: 'slot',
      label: '删除',
      value: 'remove',
      show: proxy.$permission('smartCabinetList:delete'),
    },
    {
      type: 'slot',
      label: '启用',
      value: 'enable',
      show: proxy.$permission('smartCabinetList:enable'),
    },
    {
      type: 'slot',
      label: '删除',
      value: 'disable',
      show: proxy.$permission('smartCabinetList:disable'),
    },
  ],
})

const clearType = ref(true)
const slipSelectRequest = ref(true)
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  selections: [],
  data: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('smartCabinetList:update'),
        ifRender(row) {
          return row.status === 0
        },
      },
      {
        label: '启用',
        event: enable,
        show: proxy.$permission('smartCabinetList:enable'),
        ifRender(row) {
          return row.status === 0
        },
      },
      {
        label: '停用',
        event: disable,
        show: proxy.$permission('smartCabinetList:disable'),
        ifRender(row) {
          return row.status === 1
        },
      },
      {
        label: '绑定产品',
        event: binding,
        show: proxy.$permission('smartCabinetList:binding'),
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('smartCabinetList:delete'),
        ifRender: function (row) {
          return row.status === 0
        },
      },
    ],
  },
})
// 表单相关
//新增或更新相关
const modifyInfo = ref({
  visible: false,
  title: '',
})
const bindingProductInfo = ref({
  visible: false,
  title: '',
  id: '',
  type: '',
})
const detailsInfo = ref({
  visible: false,
  id: '',
})

const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const preferenceInfo = ref({
  visible: false,
})

const page = ref({
  page: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const canRemove = computed(() => {
  return (
    tableInfo.value.selections.length &&
    !tableInfo.value.selections.filter((item) => item.status !== 0).length
  )
})
const canEnable = computed(() => {
  return (
    tableInfo.value.selections.length &&
    !tableInfo.value.selections.filter((item) => item.status !== 0).length
  )
})
const canDisable = computed(() => {
  return (
    tableInfo.value.selections.length &&
    !tableInfo.value.selections.filter((item) => item.status !== 1).length
  )
})
onBeforeMount(() => {
  let obj = {
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'new_enabled_type',
      show: false,
      hidden: true,
    },
    typeValue: {
      label: '类型',
      value: 'typeValue',
      asValue: 'type',
      componentType: 'select-model',
      code: 'smart_cabinet_type',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
})

const pageInfo = (obj) => {
  page.value = obj
}

// 获取列表
const getList = () => {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
// 创建
function create() {
  modifyInfo.value.id = null
  modifyInfo.value.visible = true
  modifyInfo.value.title = '新增智能柜'
  modifyInfo.value.type = 'create'
}
// 编辑
function update(row) {
  sessionStorage.setItem('storeRowId', row.id)
  bindingProductInfo.value.id = row.id
  bindingProductInfo.value.visible = true
  bindingProductInfo.value.title = '修改智能柜'
  bindingProductInfo.value.type = 'update'
}
function binding(row) {
  //绑定产品
  sessionStorage.setItem('storeRowId', row.id)
  bindingProductInfo.value.id = row.id
  bindingProductInfo.value.visible = true
  bindingProductInfo.value.title = '绑定智能柜产品'
  bindingProductInfo.value.type = 'binding'
}
// 删除
function remove(row = undefined) {
  if (row && row.id) {
    deleteSmartCabinet([row.id]).then((resp) => {
      if (resp && resp.success) {
        getList()
      }
    })
  } else {
    proxy
      .$confirm('删除后将改变数据，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        let ids = getIds(row)
        deleteSmartCabinet(ids).then((resp) => {
          if (resp && resp.success) {
            getList()
          }
        })
      })
  }
}

function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailsInfo.value.id = row.id
  detailsInfo.value.visible = true
}
function tableRowClassOtherName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}

function getIds(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map((row) => row.id)
  }
  return ids
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(slipSelect = true) {
  let param = {
    tableKey:
      'smartCabinetList-com.slip.spd.entity.vo.smartCabinet.SmartCabinetListVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      let tableFieldInfo = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )
      tableInfo.value.fieldList = tableFieldInfo.fieldList
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = slipSelect
      tableInfo.value.api = getSmartCabinetCustomizeListPage
      getList()
    }
  })
}

function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}

async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}

function returnModify() {
  if (bindingProductInfo.value.id) {
    getList()
  } else {
    search()
  }
}

function enable(row = undefined) {
  let ids = getIds(row)
  enabledSmartCabinet(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function disable(row = undefined) {
  let ids = getIds(row)
  disabledSmartCabinet(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}

async function advancedSearchCallback(obj) {
  let arr = [
    {
      asTbName: 'smart_cabinet_list',
      columnName: 'depot_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'depotAuth',
    },
    {
      asTbName: 'smart_cabinet_list',
      columnName: 'dept_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'deptAuth',
    },
  ]
  filterInfo.value.query.queryMap = {}
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
</script>

<style scoped></style>
